package CodeBehind {

import generated.webservices.*;

import mx.containers.Canvas;
import mx.controls.Button;
import mx.events.FlexEvent;

public class MObjectDetailsBase extends Canvas
{
	public var btnClose: Button;
	public var btnDelete: Button;
	public var treeTags: TagsTree;
	
	public function set detailsObject(value: MObject): void {
		_detailsObject = value;
		refreshTags();
	}
	
	[Bindable]
	protected var _detailsObject: MObject;
	
	public var tagsTree: TagTreeInfo;
	
	[Bindable]
	protected var checkedTagsTree: CheckableTagTreeInfo;
	
	public var mediaService: MediaWS;
	
	private var tagsChanged: Boolean = false;
						
	protected function init():void {
		btnClose.addEventListener(FlexEvent.BUTTON_DOWN, closeClick);
		btnDelete.addEventListener(FlexEvent.BUTTON_DOWN, deleteClick);	
		mediaService.addgetObjectTagsEventListener(objectTagsCallBack);
	
		treeTags.addEventListener(TagCheckBoxChangedEvent.CHECKBOX_CHANGED, tagChanged);
	}
	
	private function objectTagsCallBack(event: GetObjectTagsResultEvent): void {
		checkedTagsTree = new CheckableTagTreeInfo(tagsTree, event.result); 
	}
	
	private function closeClick(event: FlexEvent): void {
		dispatchEvent(new Event("detailsClosed"));
		if (tagsChanged)
			dispatchEvent(new MObjectEvent(MObjectEvent.OBJECT_CHANGED, _detailsObject));
		detailsObject = null;						
	}
	
	private function deleteClick(event: FlexEvent): void {
		mediaService.deleteObject(_detailsObject.ID);
		closeClick(event);
		dispatchEvent(new MObjectEvent(MObjectEvent.DELETE_OBJECT, _detailsObject));	
	}
	
	private function tagChanged(event: TagCheckBoxChangedEvent): void {
		if (event.item.data) {
			var objID: Number = _detailsObject.ID;
			var tagID: Number = (event.item.data as CheckableTagTreeInfo).ID;
			if (event.item.checked) {
				mediaService.assignTagToObject(objID, tagID);
			}
			else {
				mediaService.unAssignTagFromObject(objID, tagID);
			}
		}
		tagsChanged = true;
	}
	
	private function refreshTags(): void {
		if (_detailsObject)
			mediaService.getObjectTags(_detailsObject.ID);
		else
			checkedTagsTree = null;
	}
}
}